# USB测试程序的Makefile
# 支持多平台编译：gcc、riscv64-anyka-linux-musl-gcc、arm-nextvpu-linux-gnueabihf-gcc

# 默认编译器设置
CC = gcc
CFLAGS = -Wall -Wextra -std=c99 -O2
LDFLAGS = -lm -lrt

# 可选的libusb支持
ifdef USE_LIBUSB
    CFLAGS += -DHAVE_LIBUSB
    LDFLAGS += -lusb-1.0
endif

# 目标文件
TARGET = usb_test
TARGET_ARM = usb_test_arm
TARGET_RISCV64 = usb_test_riscv64

# 源文件
SRCS = main.c usb_utils.c
OBJS = $(SRCS:.c=.o)
OBJS_ARM = $(SRCS:.c=.o_arm)
OBJS_RISCV64 = $(SRCS:.c=.o_riscv64)

# 头文件
HEADERS = usb_utils.h

# 默认目标
all: $(TARGET)

# GCC编译 (本地)
$(TARGET): $(OBJS)
	$(CC) $(CFLAGS) -o $@ $(OBJS) $(LDFLAGS)

%.o: %.c $(HEADERS)
	$(CC) $(CFLAGS) -c $< -o $@

# ARM交叉编译
$(TARGET_ARM): $(OBJS_ARM)
	arm-nextvpu-linux-gnueabihf-gcc $(CFLAGS) -o $@ $(OBJS_ARM) $(LDFLAGS)

%.o_arm: %.c $(HEADERS)
	arm-nextvpu-linux-gnueabihf-gcc $(CFLAGS) -c $< -o $@

# RISC-V 64位交叉编译
$(TARGET_RISCV64): $(OBJS_RISCV64)
	riscv64-anyka-linux-musl-gcc $(CFLAGS) -o $@ $(OBJS_RISCV64) $(LDFLAGS)

%.o_riscv64: %.c $(HEADERS)
	riscv64-anyka-linux-musl-gcc $(CFLAGS) -c $< -o $@

# 编译所有平台
all_platforms: $(TARGET) $(TARGET_ARM) $(TARGET_RISCV64)

# ARM平台编译
arm: $(TARGET_ARM)

# RISC-V平台编译
riscv64: $(TARGET_RISCV64)

# 带libusb支持的编译
libusb: USE_LIBUSB=1
libusb: $(TARGET)

# 调试版本
debug: CFLAGS += -g -DDEBUG -DUSB_DEBUG_ENABLED=1
debug: $(TARGET)

# 清理规则
clean:
	rm -f $(TARGET) $(TARGET_ARM) $(TARGET_RISCV64)
	rm -f *.o *.o_arm *.o_riscv64
	rm -f core

# 安装规则（可选）
install: $(TARGET)
	cp $(TARGET) /usr/local/bin/
	chmod +x /usr/local/bin/$(TARGET)

# 卸载规则（可选）
uninstall:
	rm -f /usr/local/bin/$(TARGET)

# 测试规则
test: $(TARGET)
	@echo "运行USB系统信息查询..."
	@./$(TARGET) --info || echo "需要在支持USB的系统上运行"
	@echo "运行USB设备扫描..."
	@./$(TARGET) -m scan || echo "需要USB设备"

# 代码检查
check:
	@echo "检查代码语法..."
	@gcc -Wall -Wextra -std=c99 -fsyntax-only $(SRCS)
	@echo "语法检查通过"

# 生成依赖关系
depend:
	@gcc -MM $(SRCS) > .depend

# 显示帮助
help:
	@echo "USB测试程序编译帮助"
	@echo "===================="
	@echo "make              - 编译本地版本 (gcc)"
	@echo "make arm          - 编译ARM版本"
	@echo "make riscv64      - 编译RISC-V 64位版本"
	@echo "make all_platforms - 编译所有平台版本"
	@echo "make libusb       - 编译带libusb支持的版本"
	@echo "make debug        - 编译调试版本"
	@echo "make clean        - 清理编译文件"
	@echo "make install      - 安装到系统"
	@echo "make uninstall    - 从系统卸载"
	@echo "make test         - 运行测试"
	@echo "make check        - 语法检查"
	@echo "make help         - 显示此帮助"
	@echo ""
	@echo "环境变量:"
	@echo "USE_LIBUSB=1      - 启用libusb支持"

# 包含依赖关系文件
-include .depend

# 伪目标声明
.PHONY: all all_platforms arm riscv64 libusb debug clean install uninstall test check depend help